/** 
 * @description 具备CRUD 操作的列表页面 ，在Rsd.view.ListDialog 基础上添加modelType和schema属性
 * @description BizController 配合使用，有规定的参数格式
 * */
Rsd.define('Rsd.zen.dialog.BizListDialog', {
    extend: 'Rsd.zen.dialog.ListDialog',
    requires: [
        'Rsd.control.SearchToolBar',
        'Rsd.form.ComboBoxEnum'
    ],
    xtype: 'biz-list-dialog',
    readonly: false,
    form:{
        viewType:'Rsd.zen.dialog.BizFormDialog'
    },
    /**
     * @description 对象模型，用户于取Rsd.data.ModelSchema(集成了模型结构以及对象的CURD操作)对象
     * @description 优先从页面中获取，不存在时，从该页面菜单中获取
     */
    //modelType:'',
    /**
     * 对象类型结构 在需要时，自动通过 Rsd.app.getSchema(modelType)获取
     */
    //modelSchema:null, 
    /**
    *  @description 合并到父类属性 formFields后使用
    * */
    fields: [],
    /**
    *  @description 合并到父类属性 gridColumns后使用
    * */
    columns: [],

    /**
     *  @description 列表数据字段名
     */
    listMember: '',
    /**
     * 
     */
    opColumns: [
        {
            name: 'edit',
            text: '操 作',
            nobr: true,
            width: 120,
            fixed: true,
            xtype: 'template',
            format: 'rowOpFormat'
        }, 
        {
            name: 'space',
            text: '',
            xtype: 'template',
            width: 5,
            fixed: true,
            hideable: false,
            sortable: false
        }
    ],

    /**
     * 
     */
    autoLoad: false,
    /**
     *  @description 工具栏上 增加的按钮,[{text:'ok',handler:'btn_ok'}]
     */
    newButtons: [],
   /**
     * @description 操作列按钮,'edit','br','delete'
     * 元素支持类型：
     *   string:edit or delete ,
     *   object: 
     *      {
     *          text:'查看',
     *          image:'',
     *          express:'{{=name}}=="tom"',
     *          handler:function(){},
     *      }
     */
    opButtons:['edit','delete'],
    /**
    * 
    * */
    constructor: function BizListDialog(config) {
        config = config || {};
        this.apply(config); 
    },
    /**
    * */
    onBeforeInit: function onBeforeInit() {
 
        this.callParent(); 
        var me = this; 
         
        //handler 是cqrs 对象 
        me.isSchemaLoading = true;
         
        if(!me.modelType)
        {
            return;
        }
        //提前请求
        me.handler.getSchema(function(modelSchema){
            if(modelSchema==null)
            { 
                alert('未获取到schema：' + me.modelType);
                return;
            }
            me.schemaIsLoading = false;
            me.modelSchema = modelSchema;
             
            if (me.gridColumns.length == 0) {
                me.gridColumns = modelSchema.getColumns(me.columns || []); 
            }

            if (me.formFields.length == 0) {
                me.formFields = modelSchema.getFields(me.fields || []);
            }

            //设计模式参数设置
            if(me.mode == 'design')
            {
                me.modelSchema.columns.map((p)=>{
                        p['design']=true;
                        p['designHandler']= function(col){
                            if(me.designHandler)
                            {
                                me.funApplyByIOC(me.designHandler,["column",col])
                            }
                            else
                            {
                                alert('属性designHandler未设置');
                            } 
                        };
                });
                //console.log(me.modelSchema);
            }
            
            me.isSchemaLoading=false;
            me.fire('schemaLoaded',[modelSchema]);

            me.callParentFn('onBeforeInit');
        }); 

        //表格和表单的schema可能不一致，如：当表格是视图，表单是table时，form和list 的schema不一致
        //加载表单schema,
        if (this.form.modelType) {
           
            Rsd.app.getSchema(this.form.modelType, function (modelSchema) {
                me.formSchema = modelSchema;
            });
        }
  
    },

    /**
    *
    * */
    onBeforeRender: function onBeforeRender() {

        this.menu = this.menu || {};
        //debugger; 
        var me = this;
        var curd = me.modelSchema && me.modelSchema.curd;
        if(me.readonly)
        {
            curd = 4;
        }
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        //功能按钮
        if(me.newButtons.length == 1 && (curd&1)===1)
        {
           me.newButtons.push({ text: '新 增', handler: 'btn_newItem' });
        }
      
        var newBtns = me.newButtons||[]; 
        for(var i in newBtns)
        {
            if(newBtns[i] == 'new'|| newBtns[i] =='add')
            {
                me.newButtons[i] = { text: '新 增', handler: 'btn_newItem' }; 
            }
        }
        //操作列
        var hasOpBtn = false;
        var opBtns = this.opButtons || [];
        for (var i in opBtns) {
            var item = opBtns[i];
            if (Rsd.isString(item)) {

                if (item.toLowerCase() == 'edit' && (curd & 2)==2) {
                    hasOpBtn = true;
                    break;
                }

                if (item.toLowerCase() == 'delete' && (curd & 8)==8) {
                    hasOpBtn = true;
                    break;
                } 
                continue;
            } 
            hasOpBtn = true;
            break;
        }
        if(hasOpBtn==false)
        {
            this.opColumns = [{
                name: 'space',
                text: '',
                xtype: 'template',
                width: 5,
                fixed: true,
                hideable: false,
                sortable: false
            }];
        }

        //设计模式参数设置
        if (me.mode == 'design') {
            me.newButtons.push({
                xtype:'link',
                label:false,
                text:'添加按钮',
                width:'80px',
                style:{
                    cursor:'pointer',  
                    lineHeight: 25,
                    borderRadius: '40px',
                    backgroundColor: '#0c25eccc',
                    color: '#FFF',
                    textAlign: 'center'
                },
                handler:function(){
                    //
                    if(me.designHandler)
                    {
                        me.funApplyByIOC(me.designHandler,["button"])
                    }
                    else
                    {
                        alert('属性designHandler未设置');
                    }
                    
                }
            });
        }

        //查询添加列  
        for (var i in me.searchColumns) {
            var _c = me.searchColumns[i];
            _c.xtype = _c.xtype || 'text';
            _c.label = { content: _c.label || _c.text, height: 30 };
            _c.dataIndex = _c.dataIndex || _c.name;
            _c.name = _c.name || _c.dataIndex;
            _c.margin = _c.margin || "0 0 0 20";
        }
       //设计模式参数设置
       if (me.mode == 'design') {
            
            me.searchColumns.push({
                xtype:'link',
                label:false,
                text:'添加筛选条件', 
                style:
                {
                    cursor:'pointer',  
                    lineHeight: 25,
                    borderRadius: '40px',
                    backgroundColor: '#2dac08f0',
                    color: '#FFF',
                    textAlign: 'center'
                },
                handler:function(){
                    //
                    if(me.designHandler)
                    {
                        me.funApplyByIOC(me.designHandler,["search"])
                    }
                    else
                    {
                        alert('属性designHandler未设置');
                    } 
                }
            });
        }
       
        me.callParentFn('onBeforeRender');
        return this;
    },
    /*
    *
    * */
    load: function load(args, callback) {

        var me = this;
      
        if(me.isSchemaLoading)
        {
            me.on('schemaLoaded',function(){me.load(args,callback);});
        }
        

        var _args = args || {};
        var _fn_callback = function(data){
            if(callback)
            {
                callback(data);
            }
            me.____lastWhere = me.toolBar && me.toolBar.getWhere();
        };
        if(Rsd.isArray(_args))
        {
             me.callParentFn("load",[_args, _fn_callback]);
            return;
        }
        //数据源 属性
        if (this.dataSource) {
            me.callParentFn("load", [this.dataSource, _fn_callback]);
            return;
        } 
        //
        var _serviceName = me.serviceName || me.menu.serviceName;
        if(_serviceName)
        {
            var _service = Rsd.app.getService(_serviceName);
            me.dataStore = Rsd.create('Rsd.data.Store', { proxy: _service, listName: me.listMember || me.menu.listMember || 'rows' });
            me.callParentFn("load", [_args, _fn_callback]);
            return;
        }
        //dataStore对象,Rsd.data.Store数据源，支持本地数据已本地缓存数据
        if (me.dataStore) {
            me.callParentFn("load", [_args, _fn_callback]);
            return;
        }
        
        //cqrs  
        var opt = me.getPagingOpt();  
        _args = Rsd.apply(args||{}, {
            modelType: me.modelType,
            pageSize: opt.pageSize || 100,
            pageIndex: opt.pageIndex || 0
        }); 
        _args.where =  Rsd.arrayConcat(_args.where,me.where, me.menu && me.menu.where,me.toolBar && me.toolBar.getWhere()),
        _args.sort = Rsd.arrayConcat(_args.sort, me.sort, me.menu && me.menu.sort); 
        me.handler.list(_args,function(data){
            _fn_callback(data);
        });  
        return this;
    },

    /*
     * */
    rowOpFormat: function rowOpFormat(row) {
        if (this.readonly) {
            return [];
        }
        var me = this;
        var curd = me.modelSchema && me.modelSchema.curd;
        if(me.readonly)
        {
            curd = 4;
        }
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        var btns = [];
        var opBtns = this.opButtons||[];
        for(var i in opBtns)
        {
            var item = opBtns[i];
            if(Rsd.isString(item))
            {
                if(item.toLowerCase() == 'edit')
                {
                    if((curd & 2)==2)
                    {
                        var btnEdit = me.editButton(row);
                        btns.push(btnEdit);
                    } 
                    continue;
                }

                if(item.toLowerCase() == 'delete')
                {
                    if((curd & 8)==8)
                    {
                        var btnDel = me.deleteButton(row);
                        btns.push(btnDel);
                    } 
                    continue;
                }
                if(item.toLowerCase() == 'br')
                {
                    btns.push(document.createElement('br'));
                    continue;
                }
                continue;
            }

            if(Rsd.isObject(item))
            {
                var express = item.express
                if(Rsd.isEmpty(express)|| eval(Rsd.template(express,row)))
                {
                    var _fn = item.handler || item.onclick || item.fn;
                    var btn = document.createElement(_fn?'a':'label');
                  
                    btn.innerHTML = item.text;
                    btn.style.display = 'inline-table';
                    btn.style.width = '45px';
                    btn.style.textAlign = "right";
                    btn.style.margin = "0 5px 0 5px";
                    if(item.image || item.img)
                    {
                        btn.style.backgroundImage = 'url(' + item.image||item.img + ')';
                        btn.style.backgroundPosition = 'left center';
                        btn.style.backgroundSize = '12px';
                        btn.style.backgroundRepeat = 'no-repeat';
                    } 
                    if(_fn)
                    {
                        btn.href = '#';
                        btn.handler = _fn;
                        btn.onclick = function () {
                            me.funApplyByIOC(this.handler, [row, me]);
                        };
                    }
                    
                    btns.push(btn);
                }
                
                continue; 
            }
        }
        
        return btns; 
    },
    /**
     * 
     * @param {*} row 
     * @param {*} style 
     * @returns 
     */
    editButton: function editButton(row,style) {
        
        var me = this;
        var btnEdit = document.createElement('a');
        btnEdit.href = '#';
        btnEdit.innerHTML = '修改';
        btnEdit.style.display = 'inline-table';
        btnEdit.style.width = '45px';
        btnEdit.style.textAlign = "right";
        btnEdit.style.margin = "0 5px 0 5px";
        btnEdit.style.backgroundImage = 'url(' + Rsd.getRedjsHost() + "/resources/svg/update.svg" + ')';
        btnEdit.style.backgroundPosition = 'left center';
        btnEdit.style.backgroundSize = '12px';
        btnEdit.style.backgroundRepeat = 'no-repeat';
        me.setElStyle(btnEdit,style);
        btnEdit.onclick = function () {
            me.editItem(row);
        };

        return btnEdit;
    },
    /**
     * 
     * @param {*} row 
     * @param {*} style 
     * @returns 
     */
    deleteButton: function deleteButton(row,style) {

        var me = this;
        var btnDel = document.createElement('a'); 
        btnDel.href = '#';
        btnDel.innerHTML = '删除';
        btnDel.style.display = 'inline-table';
        btnDel.style.width = '45px';
        btnDel.style.textAlign = "right";
        btnDel.style.margin = "0 5px 0 5px";
        btnDel.style.backgroundImage = 'url(' + Rsd.getRedjsHost() + "/resources/svg/delete.svg" + ')';
        btnDel.style.backgroundPosition = 'left center';
        btnDel.style.backgroundSize = '12px';
        btnDel.style.backgroundRepeat = 'no-repeat';
        me.setElStyle(btnDel,style);
        btnDel.onclick = function () {
            me.deleteItem(row);
        };
        return btnDel;
    },
    /**
     * @description 用于绑定按钮事件
     */
    btn_newItem: function btn_newItem(btn, evt) {
        
        this.newItem(this.form.data||{});//form.data 新增时表单data默认值
    },
    /**
    * @description 查看对象
     * */
    viewItem: function viewItem(record) {
        this.showItem(record || {}, true);
    },
    /**
     * @description 新增对象
     * @param record 新增对象的默认信息
     */
    newItem: function newItem(record) {
        if(record && record.$className == "Rsd.form.Button")
        {
            Rsd.alert("[新增]按钮应绑定btn_newItem事件");
            return;
        }
        this.showItem(record || {}, false);
    },
    /**
     * @description 编辑对象
     *  */
    editItem: function editItem(record) {

        this.showItem(record || {}, false);
    },

    /**
     * @description 删除
     * */
    deleteItem: function (record) {
        var me = this;
        if (record == null) {
            return;
        }
        if (confirm('确认删除该记录?')) {
            me.modelSchema.deleteObject(record,function(resp){
                if (resp.success)
                {
                    Rsd.popup('数据已删除');
                    me.load();
                }else
                {
                    Rsd.alert('数据删除失败', resp.msg);
                }
                
            });
        }

    },
    /*
     * */
    rowDblClick: function rowDblClick(row, evt) {
        if (this.readonly) {
            this.viewItem(row);
        } else {
            this.editItem(row);
        }

    }

}, function (type) {

    //modelType
    var _modelTypeGetter = function () {

        if (Rsd.isEmpty(this.__modelType)) {
            this.__modelType = this.menu.modelType;
        }
        return this.__modelType;
    };
    var _modelTypeSetter = function (value) {

        this.__modelType = value;

    };
    //biz.list 接口参数modelType
    this.defineProperty(type, "modelType", _modelTypeGetter, _modelTypeSetter, false);
    //biz.list 接口参数sort
    this.defineProperty(type, 'sort', function () { return this.__sort || []; }, function (sort) {
        this.__sort = sort;
    }, false);
    //biz.list 接口参数where
    this.defineProperty(type, 'where', function () { return this.__where || []; }, function (where) {
        this.__where = where;
    }, false);

    var _handlerGetter = function () {

            if (!this.__handler) {
                this.__handler = Rsd.create('Rsd.cqrs.List', {owner: this });
            }
            return this.__handler;

        };

    var _handlerSetter = function (value) {

            if (Rsd.isString(value)) {
                this.__handler = Rsd.widget(value, {owner: this });;
                return;
            }
            this.__handler = value;
        }

    this.defineProperty(type, "handler", _handlerGetter, _handlerSetter, true);
});